import React from "react";
import { isValidJson } from "@/lib/utils";
import { ColumnFilter, ColumnSort } from "@tanstack/react-table";
import { useCallback } from "react";
import { useSearchParams } from "react-router-dom";

export type TableSearchParamsT = {
  pageIndex: number;
  pageSize: number;
  search?: string;
  sorting: ColumnSort[];
  columnFilters: ColumnFilter[];
};

export const useTableSearchParams = () => {
  const [pageIndex, setPageIndex] = React.useState<number>(0);
  const [pageSize, setPageSize] = React.useState<number>(10);
  const [search, setSearch] = React.useState<string>();
  const [sorting, setSorting] = React.useState<ColumnSort[]>([]);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFilter[]>([]);

  const setTableSearchParams = useCallback(
    (params: Partial<TableSearchParamsT>) => {
      if ("pageIndex" in params) {
        setPageIndex(params.pageIndex || 0);
      }
      if ("pageSize" in params) {
        setPageSize(params.pageSize || 10);
      }
      if ("search" in params) {
        setSearch(params.search || "");
      }
      if ("sorting" in params) {
        setSorting(params.sorting || []);
      }
      if ("columnFilters" in params) {
        setColumnFilters(params.columnFilters || []);
      }
    },
    [pageIndex, pageSize, search, sorting, columnFilters]
  );

  return {
    pageIndex,
    pageSize,
    search,
    sorting,
    columnFilters,
    setTableSearchParams,
  };
};
